﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FloodFree.Common;
using FloodFree.Web.Areas.Admin.ViewModels;
using System.Data.Entity.Infrastructure;
using System.Data.SqlClient;

namespace FloodFree.Web.Areas.Admin.Controllers
{
    public class SensorsController : BaseController
    {
        public ActionResult Index()
        {
            if (TempData["ViewData"] != null)
            {
                ViewData = (ViewDataDictionary)TempData["ViewData"];
            }
            List<Sensor> sensors = db.Sensors.Include("City").ToList();
            return View(sensors);
        }

        public ActionResult Show(int id)
        {
            Sensor sensor = db.Sensors
                            .Include("Updates")
                            .Where(x => x.SensorId == id)
                            .FirstOrDefault();

            return View(sensor);
        }

        [HttpGet]
        public ActionResult Create()
        {
            ViewBag.Cities = db.Cities.ToList();
            Sensor sensor = new Sensor();
            return View(sensor);
        }

        [HttpPost]
        public ActionResult Create(Sensor sensor)
        {
            try
            {
                sensor.City = db.Cities.Where(c => c.Id.Equals(sensor.City.Id)).First();
                db.Sensors.Add(sensor);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Erro ao criar o registro");
            }

            ViewBag.Cities = db.Cities.ToList();
            return View(sensor);
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            Sensor sensor = (from Sensor s in db.Sensors
                             where s.SensorId.Equals(id)
                             select s).First();

            if (sensor == null)
            {
                return HttpNotFound();
            }

            List<City> cities = (from City c in db.Cities
                                 select c).ToList();

            SensorAddViewModel vm = new SensorAddViewModel();
            vm.Cities = cities;
            vm.Sensor = sensor;
            return View(vm);
        }

        [HttpPost]
        public ActionResult Edit(int id, SensorAddViewModel model)
        {
            try
            {
                Sensor sensor = db.Sensors.Where(x => x.SensorId.Equals(id)).First();
                sensor.SensorUUID = model.Sensor.SensorUUID;
                sensor.Latitude = model.Sensor.Latitude;
                sensor.Longitude = model.Sensor.Longitude;
                sensor.Address = model.Sensor.Address;
                sensor.City = db.Cities.Where(x => x.Id.Equals(model.Sensor.City.Id)).First();
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "Erro ao atualizar o registro");
            }

            List<City> cities = (from City c in db.Cities
                                 select c).ToList();
            model.Cities = cities;

            return View(model);
        }


        [HttpGet]
        public ActionResult Delete(int id)
        {
            Sensor sensor = db.Sensors
                .Include("Updates")
                .Where(x => x.SensorId == id)
                .First();

            if (sensor != null)
            {
                try
                {
                    foreach (SensorUpdate update in sensor.Updates)
                    {
                        db.SensorUpdates.Remove(update);
                    }

                    db.Sensors.Remove(sensor);
                    db.SaveChanges();

                }
                catch (DbUpdateException e)
                {
                    SqlException s = e.InnerException.InnerException as SqlException;
                    if (s != null && s.Number == 547)
                    {
                        ModelState.AddModelError(string.Empty,
                            string.Format("Não é possível remover pois registor filhos cadastrados."));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Erro ao remover o registro");
                    }
                }

            }
            

            TempData["ViewData"] = ViewData;
            return RedirectToAction("Index");
        }

    }
}
